/**
 * 字段配置解析工具
 * 用于解析后台字段配置JSON数据
 */

import type {CodegenColumnDTO} from '@/api/codegen'

/**
 * 后台字段配置接口（与用户提供的JSON结构对应）
 */
export interface BackendFieldConfig {
  columnName: string
  columnType: string
  columnLength: number
  columnScale: number
  columnComment: string
  isPrimaryKey: boolean
  isAutoIncrement: boolean
  isNullable: boolean
  defaultValue: string | null
  javaFieldName: string
  javaFieldType: string
  showInList: boolean
  showInForm: boolean
  showInQuery: boolean
  queryType: string
  formType: string
  onUpdateCurrentTimestamp: boolean
  extra: string | null
}

/**
 * 解析后台字段配置JSON数据
 * @param backendConfig 后台字段配置数组
 * @returns 前端可用的字段配置数组
 */
export function parseFieldConfig(backendConfig: BackendFieldConfig[]): CodegenColumnDTO[] {
  return backendConfig.map(field => ({
    columnName: field.columnName || '',
    columnType: field.columnType || 'VARCHAR',
    columnLength: field.columnLength || 255,
    columnScale: field.columnScale || 0,
    isNullable: field.isNullable !== false, // 默认可空
    columnComment: field.columnComment || '',
    defaultValue: field.defaultValue || '',
    isPrimaryKey: field.isPrimaryKey || false,
    isAutoIncrement: field.isAutoIncrement || false,
    javaFieldType: field.javaFieldType || 'String',
    javaFieldName: field.javaFieldName || '',
    showInList: field.showInList !== false, // 默认显示在列表
    showInForm: field.showInForm !== false, // 默认显示在表单
    showInQuery: field.showInQuery || false,
    queryType: field.queryType || '=',
    formType: field.formType || 'input',
    onUpdateCurrentTimestamp: field.onUpdateCurrentTimestamp || false,
    extra: field.extra || ''
  }))
}

/**
 * 将前端字段配置转换为后台格式
 * @param frontendConfig 前端字段配置数组
 * @returns 后台格式的字段配置数组
 */
export function convertToBackendFormat(frontendConfig: CodegenColumnDTO[]): BackendFieldConfig[] {
  return frontendConfig.map(field => ({
    columnName: field.columnName,
    columnType: field.columnType,
    columnLength: field.columnLength,
    columnScale: field.columnScale,
    columnComment: field.columnComment,
    isPrimaryKey: field.isPrimaryKey,
    isAutoIncrement: field.isAutoIncrement,
    isNullable: field.isNullable,
    defaultValue: field.defaultValue || null,
    javaFieldName: field.javaFieldName,
    javaFieldType: field.javaFieldType,
    showInList: field.showInList,
    showInForm: field.showInForm,
    showInQuery: field.showInQuery,
    queryType: field.queryType,
    formType: field.formType,
    onUpdateCurrentTimestamp: field.onUpdateCurrentTimestamp,
    extra: field.extra || null
  }))
}

/**
 * 验证字段配置数据
 * @param config 字段配置数组
 * @returns 验证结果
 */
export function validateFieldConfig(config: BackendFieldConfig[]): {
  isValid: boolean
  errors: string[]
} {
  const errors: string[] = []
  
  if (!Array.isArray(config)) {
    errors.push('字段配置必须是数组格式')
    return { isValid: false, errors }
  }
  
  if (config.length === 0) {
    errors.push('字段配置不能为空')
    return { isValid: false, errors }
  }
  
  // 检查重复字段名
  const columnNames = config.map(field => field.columnName?.toLowerCase()).filter(Boolean)
  const duplicates = columnNames.filter((name, index) => columnNames.indexOf(name) !== index)
  if (duplicates.length > 0) {
    errors.push(`存在重复字段: ${[...new Set(duplicates)].join(', ')}`)
  }
  
  // 检查必填字段
  config.forEach((field, index) => {
    if (!field.columnName) {
      errors.push(`第${index + 1}个字段缺少字段名`)
    }
    if (!field.columnType) {
      errors.push(`第${index + 1}个字段缺少字段类型`)
    }
    if (!field.javaFieldType) {
      errors.push(`第${index + 1}个字段缺少Java字段类型`)
    }
    if (!field.javaFieldName) {
      errors.push(`第${index + 1}个字段缺少Java字段名`)
    }
  })
  
  return {
    isValid: errors.length === 0,
    errors
  }
}

/**
 * 生成字段配置预览信息
 * @param config 字段配置数组
 * @returns 预览信息
 */
export function generateFieldPreview(config: BackendFieldConfig[]): {
  totalFields: number
  primaryKeys: string[]
  autoIncrementFields: string[]
  listFields: string[]
  formFields: string[]
  queryFields: string[]
} {
  return {
    totalFields: config.length,
    primaryKeys: config.filter(f => f.isPrimaryKey).map(f => f.columnName),
    autoIncrementFields: config.filter(f => f.isAutoIncrement).map(f => f.columnName),
    listFields: config.filter(f => f.showInList).map(f => f.columnName),
    formFields: config.filter(f => f.showInForm).map(f => f.columnName),
    queryFields: config.filter(f => f.showInQuery).map(f => f.columnName)
  }
}

/**
 * 从JSON字符串解析字段配置
 * @param jsonString JSON字符串
 * @returns 解析结果
 */
export function parseFieldConfigFromJson(jsonString: string): {
  success: boolean
  data?: CodegenColumnDTO[]
  error?: string
} {
  try {
    const backendConfig: BackendFieldConfig[] = JSON.parse(jsonString)
    
    // 验证数据
    const validation = validateFieldConfig(backendConfig)
    if (!validation.isValid) {
      return {
        success: false,
        error: validation.errors.join('; ')
      }
    }
    
    // 转换为前端格式
    const frontendConfig = parseFieldConfig(backendConfig)
    
    return {
      success: true,
      data: frontendConfig
    }
  } catch (error) {
    return {
      success: false,
      error: `JSON解析失败: ${error instanceof Error ? error.message : '未知错误'}`
    }
  }
}